// @flow
import React, { Component } from 'react'
import styles from './HistoryFre.css'
import { Spin, Button, message, Popover, Checkbox, Select, DatePicker } from 'antd'
// import R from 'ramda'
import moment from 'moment'
import HistoryLine from 'components/HistoryLineLiandong'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const Option = Select.Option
const CheckboxGroup = Checkbox.Group
const { RangePicker } = DatePicker

import type { Location } from 'react-router'
const { search } = location
const paramsString = search.substring(1)
const searchParams = new URLSearchParams(paramsString)
const requestType = searchParams.get('requestType')

type Props = {
  location: Location,
  historyCond: Object,
  deviceData: Object,
  datatypeDict: Array<Object>,
}

type States = {
  loading: boolean,
  chartData: Array<any>,
  channelData: Array<Object>,
  channelIds: Array<string>,
  dataType: string,
  historyDates: Array<any>,
  historyDataTime: string, // 快捷时间
}
class HistoryFre extends Component {
  props: Props
  state: States
  getData: Function
  getChannel: Function
  channelChange: Function
  refer: Function
  changeDatatype: Function
  changeHistoryTimeCond: Function
  changeDataTime: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      loading: false,
      chartData: [],
      channelData: [],
      channelIds: ['0'],
      dataType: '1',
      historyDates: [this.props.historyCond.startTime, this.props.historyCond.endTime],
      historyDataTime: '快捷时间'
    }
    this.getData = this.getData.bind(this)
    this.getChannel = this.getChannel.bind(this)
    this.channelChange = this.channelChange.bind(this)
    this.refer = this.refer.bind(this)
    this.changeDatatype = this.changeDatatype.bind(this)
    this.changeHistoryTimeCond = this.changeHistoryTimeCond.bind(this)
    this.changeDataTime = this.changeDataTime.bind(this)
  }

  componentWillMount () {
    this.getChannel() // 取通道后画图
  }

  changeDatatype (value: string) {
    const compoment = this
    this.setState({
      loading: true,
      dataType: value
    }, () => {
      compoment.getData(compoment.props)
    })
  }

  getChannel () {
    // 通道
    const { deviceData } = this.props
    const id = deviceData.id
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}device/devices/${id}/channel-ids`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const channelData = json.result.filter((dd) => dd.sensorType === '振动量')
        this.setState({
          channelData: channelData[0].channelIds
        }, () => {
          this.getData(this.props)
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  channelChange (values: Array<string>) {
    this.setState({
      channelIds: values
    })
  }

  refer () {
    this.getData(this.props)
  }

  getData (props: Props) {
    this.setState({
      loading: true
    })
    // let indsName = ['幅值', '相位']
    const { deviceData } = props
    const { channelIds, channelData, historyDates } = this.state
    const deviceNo = deviceData.deviceNo.split('_')
    const postBody = JSON.stringify({
      fieldGroup: 'c_vib',
      fields: ['v1x', 'p1x'],
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': this.state.dataType },
          '$or': channelIds.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      },
      timeRange: {
        start: moment(historyDates[0]).format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        end: moment(historyDates[1]).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      },
      valueFilters: [
          { '$default': { '$or': [{ '$gt': -1000000 }] } }
      ],
      size: 10000,
      page: 1
    })

    let api = `${__KMX_API__}`
    if (requestType === 'wx') {
      api = `${__WXKMX_API__}`
    }
    fetch(`${api}data-streams`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: postBody
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 0) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        loading: false
      })
      const results = json.results
      if (results && results.length > 0) {
        let data1 = [] // 幅值的数组
        let data2 = [] // 相位的数组
        results.map((data, index) => {
          const channelName = channelData.filter((dd) => String(dd.id) === String(data.compoundId.channel_id))[0].name
          data['type'] = 'line'
          data['data'] = data.streams.map((d, i) => {
            return d
          })
          data['sensorNameEn'] = 'c_vib' // 用于底部事件名称点击绘图
          data['sensorName'] = '振动量' // 用于底部事件名称点击绘图
          if (index % 2 === 0) {
            data['Title'] = '幅值'
            data['name'] = '幅值__' + channelName
            data1.push(data)
          } else {
            data['Title'] = '相位'
            data['name'] = '相位__' + channelName
            data2.push(data)
          }
        })
        this.setState({
          chartData: [
            data1,
            data2
          ]
        })
      } else {
        message.info('暂无数据')
        this.setState({
          loading: false,
          chartData:[]
        })
      }
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading: false,
        chartData:[]
      })
    })
  }

  // 快捷改变数据的时间段
  changeDataTime (value) {
    const compoment = this
    let historyDates
    if (value === '8h') {
      historyDates = [moment().subtract(8, 'h'), moment()]
    } else {
      historyDates = [moment().subtract(1, value), moment()]
    }
    this.setState({
      historyDataTime: value, // 快捷显示时间
      historyDates: historyDates // 时间显示
    }, () => {
      compoment.getData(compoment.props)
    })
  }

  changeHistoryTimeCond (dates, dateStrings) {
    this.setState({
      historyDates: dates,
      historyDataTime: '快捷时间'
    })
  }

  render () {
    const { loading, chartData, channelIds, channelData, historyDates } = this.state
    const { datatypeDict } = this.props
    return (
      <div className={styles['main']}>

        <div className={styles['condition']}>
          <RangePicker
            showTime
            format='YYYY-MM-DD HH:mm:ss'
            value={historyDates}
            onOk={() => this.refer()}
            onChange={this.changeHistoryTimeCond}
            style={{ marginLeft: 8 }}
          />
          <Select defaultValue='1'
            style={{ marginLeft: 8 }}
            placeholder='数据类型'
            onChange={this.changeDatatype}
            >
            {
              datatypeDict.map((d, i) => {
                return <Option key={i} value={d.value}>{d.label}</Option>
              })
            }
          </Select>
          <Select
            style={{ marginLeft: 8, width: 80 }}
            placeholder='快捷时间'
            value={this.state.historyDataTime}
            onChange={this.changeDataTime}
            >
            <Option value='h'>一小时</Option>
            <Option value='8h'>八小时</Option>
            <Option value='d'>一天</Option>
            <Option value='w'>一周</Option>
            <Option value='M'>一月</Option>
            <Option value='y'>一年</Option>
          </Select>
          <Popover content={
            <div>
              <div className={styles['conditionTop']}>
                <CheckboxGroup value={channelIds} options={
                  channelData.map((d, i) => {
                    return { label: d.name, value: String(d.id) }
                  })
                } onChange={this.channelChange} />
              </div>
              <p className={styles['leftFooter']}>
                <Button type='primary' onClick={this.refer} disabled={loading}>绘制</Button>
              </p>
            </div>
          } trigger='click' title='通道：'>
            <Button type='primary' className={styles['conditionBtn']}>选择指标</Button>
          </Popover>
        </div>

        <Spin spinning={loading} tip='加载中...'>
          {
            // chartData.map((item, i) => {
            //   return <div key={i} className={styles['chart-item']}>
            //     <HistoryLine
            //       chartData={item}
            //     />
            //   </div>
            // })
          }
          {
            <HistoryLine
              chartData={chartData}
            />
          }
        </Spin>
      </div>
    )
  }
}

export default HistoryFre
